package com.example.handler;

import com.example.common.ResponseCode;
import com.example.common.resp.RespJson;
import com.example.exception.BizException;
import com.example.exception.BizValidationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * <h1>全局异常统一处理</h1>
 * @author LevelCoder
 * @version V1.0.0
 * @email LevelCoder@126.com
 * @date 2019/11/22
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理Exception异常 非自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public RespJson handleException(Exception e){
        log.error(e.getMessage(), e);
        return new RespJson(ResponseCode.FAIL.getResponseCode(), ResponseCode.FAIL.getResponseMessage());
    }

    /**
     * 处理自定义异常
     * <h2>自意义异常处理方法</h2>
     * @param e  {@link BizException} 自定义异常
     * @return
     */
    @ExceptionHandler(BizException.class)
    public RespJson handleException(BizException e){
        log.error(e.getMessage(), e);
        return new RespJson(e.getResponseCode(),e.getResponseMessage());
    }

    /**
     *
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public RespJson handleRuntimeException(RuntimeException e){
        log.error(e.getMessage(), e);
        return new RespJson(ResponseCode.FAIL.getResponseCode(), ResponseCode.FAIL.getResponseMessage());
    }

    /**
     * <h2>自定义校验异常类</h2>
     * @param e
     * @return
     */
    @ExceptionHandler(BizValidationException.class)
    public RespJson handleValidationException(BizValidationException e){
        return new RespJson(e.getResponseCode(),e.getResponseMessage());
    }

}
